/**
 * 描述：http
 */
import axios from 'axios';
import { router } from '@/router/';
import store from '@/store/';
import { Message } from 'element-ui';
import { Notice } from 'iview';
import _hyTool from '@/js/core/utils/tool';

axios.defaults.timeout = 10000;

// 拦截
axios.interceptors.request.use(function (config) {
  if (_hyTool.getStore('access_token')) {
    if (config.url.indexOf('?') > -1) {
      config.url += '&access_token=' + _hyTool.getStore('access_token');
    } else {
      config.url += '?access_token=' + _hyTool.getStore('access_token');
    }
    // config.headers['x-access-token'] = _hyTool.getStore('token');
    // config.headers['userId'] = _hyTool.getCookie('userId');
  }
  return config;
}, function (error) {
  Message.error({
    message: '加载超时'
  });
  return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
  // 解决导出api返回数据不一致问题
  if (typeof response.data === 'object') {
    if (response.data.code === 200) {
      return Promise.resolve(response.data);
    } else {
      setTimeout(() => {
        _hyTool.csl(false);
        _hyTool.cal(false);
      }, 500);
      Notice.error({
        title: '请求错误',
        desc: response.data.message
      });
      return Promise.reject(response.data.message);
    }
  } else {
    if (response.status === 200) {
      return Promise.resolve(response.config);
    } else {
      Notice.error({
        title: '导出',
        desc: '导出失败！'
      });
    }
  }
}, function (error) {
  setTimeout(() => {
    _hyTool.csl(false);
    _hyTool.cal(false);
  }, 500);
  if (error.response) {
    switch (error.response.status) {
      case 401:
        // 401 清除token信息并跳转到登录页面
        store.commit('logout');
        Message.error({
          message: '登录超时， 请重新登录！'
        });
        router.replace({
          path: '/login',
          query: {redirect: router.currentRoute.fullPath}
        });
        break;
      case 404:
        return Promise.reject('当前api未找到，错误代码：404');
      case 500:
        return Promise.reject('未知原因，错误代码：500');
    }
  }
  return Promise.reject(error);
});

export default axios;
